package com.xwq.administrator.lljk;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.List;

/**
 * Created by Administrator on 2016/12/10.
 */
public class TrafficService extends Service {
    /**
     * 接受者，接受网络状态
     */
    private class TrafficReceiver extends BroadcastReceiver{
        private final String TAG=TrafficReceiver.class.getSimpleName();

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG,"网络状态改变");
            Log.i("ssss",TAG);
        }
    }
    /**
     * 用于返回本service
     */
    public class MyBinder extends Binder{
        TrafficService getService(){
            return TrafficService.this;
        }
    }

    private MyBinder myBinder=new MyBinder();//实例化，用于返回本service
    private String TAG=TrafficService.class.getSimpleName();//获取本类的名字，用于输出tag
    private DbManager dbManager;
    private ConnectivityManager connManager;
    private TrafficReceiver trafficReceiver;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    @Override
    public void onCreate() {
        Log.i(TAG,"onCreate");
        dbManager=new DbManager(this);//获取数据库连接服务
        connManager= (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);//获取网络连接服务
        //注册接受者
        trafficReceiver=new TrafficReceiver();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);//接受有网络的广播
        registerReceiver(trafficReceiver,intentFilter);

        logRecord();
        super.onCreate();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG,"onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"onstartcommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.i(TAG,"ondestory");
        unregisterReceiver(trafficReceiver);
        logRecord();
        dbManager.close();
        super.onDestroy();
    }

    /**
     * 记录有网络权限的应用的结束时间的流量情况，开始时间的流量情况
     */
    public void logRecord(){
        NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
        String networkType = null;
        if (networkInfo == null) {
            networkType = null;
        } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            networkType = DbConstants.NETWORK_TYPE_WIFI;
        } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            networkType = DbConstants.NETWORK_TYPE_MOBILE;
        }

        List<PackageInfo> packinfos = getPackageManager().getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_PERMISSIONS);
        //http://blog.csdn.net/luojiusan520/article/details/47696891
        //http://blog.csdn.net/u014729294/article/details/51822211
        for (PackageInfo info : packinfos) {
            String[] premissions = info.requestedPermissions;
            if (premissions != null && premissions.length > 0) {
                for (String premission : premissions) {
                    if ("android.permission.INTERNET".equals(premission)) {
                        int uid = info.applicationInfo.uid;
                        Log.i("sss",uid+"");
                        long rx = TrafficStats.getUidRxBytes(uid);
                        long tx = TrafficStats.getUidTxBytes(uid);
                        dbManager.updateEnd(info.packageName, System.currentTimeMillis(), rx, tx);
                        dbManager.insertStart(info.packageName, info.applicationInfo.loadLabel(getPackageManager()).toString(), System.currentTimeMillis(), networkType, rx, tx);
                    }
                }
            }
        }
    }

}
